package com.leetcode;

import com.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 113. 路径总和 II
 * 递归, 从顶到底的思维
 * 处理路径字符串, 不是很好
 *
 * @author fy
 * @date 2022/4/24 16:36
 */
public class Solution113 {

    private List<List<Integer>> res;

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        res = new ArrayList<>();
        dfs(root, targetSum, "");
        return res;
    }

    private void dfs(TreeNode node, int targetSum, String path) {
        if (node == null) {
            return;
        }
        if (node.left == null && node.right == null) {
            if (targetSum == node.val) {
                path += node.val;
                List<Integer> list = Arrays.stream(path.split(",")).mapToInt(Integer::valueOf).boxed().collect(Collectors.toList());
                res.add(list);
            }
            return;
        }
        dfs(node.left, targetSum - node.val, path + node.val + ",");
        dfs(node.right, targetSum - node.val, path + node.val + ",");
    }

}
